package com.starmark.auth.common.metaobject;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.starmark.auth.common.util.UserUtil;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.Instant;

/**
 * 通用字段填充
 */
@Component
public class CommonUserMetaObjectHandler implements MetaObjectHandler {

    /**
     * 测试 user 表 name 字段为空自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        setFieldValByName("createTime", Instant.now().toEpochMilli(), metaObject);
        setFieldValByName("updateTime", Instant.now().toEpochMilli(), metaObject);
        if (UserUtil.getCurrentUser() != null) {
            setFieldValByName("createBy", UserUtil.getUserId(), metaObject);
            setFieldValByName("updateBy", UserUtil.getUserId(), metaObject);
            setFieldValByName("projectCode", UserUtil.getCurrentUser().getProjectCode(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName("updateTime", Instant.now().toEpochMilli(), metaObject);
        if (UserUtil.getCurrentUser() != null) {
            setFieldValByName("updateBy", UserUtil.getUserId(), metaObject);
        }
    }
}
